package com.firesys.rounting.ui;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.firesys.R;
import com.firesys.dbhelper.SharedPreferenceUtil;
import com.firesys.dbhelper.XmlNameHelper;
import com.firesys.gridview.ImageSwitcherActivity;
import com.firesys.povo.DeviceItem;
import com.firesys.povo.DeviceVo;
import com.firesys.povo.SpinnerVo;
import com.firesys.rounting.Adapter.DeviceRoutingCheckAdapter;
import com.firesys.rounting.db.DeviceRoutingDao;
import com.firesys.util.BluetoothHelp;
import com.firesys.util.CHexConver;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.NfcV;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

/**
 * 巡检
 * 
 * @author King
 * 
 */
public class DeviceRoutingCheck extends Activity implements OnClickListener {

    public static final int REQUEST_CODE_PAIZHAO = 1;

    public ListView listview;

    public DeviceRoutingCheckAdapter adapter;

    public Button button;// 保存

    public Button button1;// 拍照

    public Button button2;// 读卡

    public TextView textinfo;// 统计信息

    // public Spinner spinner1;//阀门状态
    public Spinner spinner2;// 阀门启用状态
    //
    // public String devicstatus="请选择";
    public String openstatus = "0";
    //
    // public String[] data1=new String[]{"请选择","好","一般","差"};
    public List<SpinnerVo> data2 = new ArrayList<SpinnerVo>();
    public List<Integer> info = new ArrayList<Integer>();

    public List<DeviceItem> item = new ArrayList<DeviceItem>();// 当前设备册的

    public DeviceRoutingDao dao;

    public SharedPreferenceUtil sp;

    public long time;
    public boolean isStop = false;
    private String rfidNumber;

    private NfcAdapter mAdapter;
    private PendingIntent mPendingIntent;
    private IntentFilter[] mFilters;
    private String[][] mTechLists;

    public DeviceVo device;// 一个设备信息

    public TextView textview2;// 设备编号
    public TextView textview3;// 设备地址
    public TextView textview4;// 公称口径
    public TextView textview5;// 设备类型

    public EditText edit;// 备注

    public int total = 0;
    public int nocopytotal = 0;
    public boolean isSave = false;
    public String devicelistid;

    public BluetoothHelp bluehelp;
    public boolean isNfc=false;
    public String readtype;// 读卡方式

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.device_routing_check_rfid);
	devicelistid = getIntent().getStringExtra("devicelistid");
	sp = new SharedPreferenceUtil(this);
	readtype=sp.getValue(XmlNameHelper.readtype);
	bluehelp=new BluetoothHelp(this);
	bluehelp.init();
	dao = new DeviceRoutingDao(this, sp.getValue(XmlNameHelper.SqliteName));
	data2 = dao.queryOpenStatus();
	textinfo = (TextView) findViewById(R.id.device_routing_check_rfid_info);
	textview2 = (TextView) findViewById(R.id.device_routing_check_rfid_number);
	textview3 = (TextView) findViewById(R.id.device_routing_check_rfid_adds);

	textview4 = (TextView) findViewById(R.id.device_routing_check_rfid_devicecaliber);
	textview5 = (TextView) findViewById(R.id.device_routing_check_rfid_devicetype);

	edit = (EditText) findViewById(R.id.device_routing_check_rfid_remark);
	mAdapter = NfcAdapter.getDefaultAdapter(DeviceRoutingCheck.this);
	mPendingIntent = PendingIntent.getActivity(DeviceRoutingCheck.this, 0, new Intent(DeviceRoutingCheck.this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
	IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
	try {
	    ndef.addDataType("*/*");
	    mFilters = new IntentFilter[] { ndef, };
	    mTechLists = new String[][] { new String[] { NfcV.class.getName() }, new String[] { MifareClassic.class.getName() } };

	} catch (MalformedMimeTypeException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
	button = (Button) findViewById(R.id.device_routing_check_rfid_save);
	button1 = (Button) findViewById(R.id.device_routing_check_rfid_tag);
	button2 = (Button) findViewById(R.id.device_routing_check_rfid_paizhao);
	button.setOnClickListener(this);
	button1.setOnClickListener(this);
	button2.setOnClickListener(this);
	// spinner1=(Spinner)findViewById(R.id.device_routing_check_rfid_status);
	spinner2 = (Spinner) findViewById(R.id.device_routing_check_rfid_openstatus);
	ArrayAdapter<SpinnerVo> adapter2 = new ArrayAdapter<SpinnerVo>(DeviceRoutingCheck.this, android.R.layout.simple_spinner_item, data2);
	adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);// 设置打开方式
	spinner2.setAdapter(adapter2);
	// spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
	//
	// @Override
	// public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
	// long arg3) {
	// devicstatus=arg0.getItemAtPosition(arg2).toString();
	//
	// }
	//
	// @Override
	// public void onNothingSelected(AdapterView<?> arg0) {
	// // TODO Auto-generated method stub
	//
	// }
	// });
	spinner2.setOnItemSelectedListener(new OnItemSelectedListener() {

	    @Override
	    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		SpinnerVo spinner = (SpinnerVo) arg0.getSelectedItem();
		openstatus = spinner.getKey();

	    }

	    @Override
	    public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub

	    }

	});
	listview = (ListView) findViewById(R.id.device_routing_check_rfid_listview);
	item = new ArrayList<DeviceItem>();
	info = new ArrayList<Integer>();

	adapter = new DeviceRoutingCheckAdapter(item, info, this);
	listview.setAdapter(adapter);

    }

    @Override
    public void onClick(View v) {
	switch (v.getId()) {
	case R.id.device_routing_check_rfid_save:
	    if (device == null) {
		Toast.makeText(DeviceRoutingCheck.this, "请先读卡确认此设备！", Toast.LENGTH_SHORT).show();
		return;
	    }
	    if (isSelectAll(adapter.getInfo())) {
		isSave = true;
		Intent intent = new Intent(DeviceRoutingCheck.this, ImageSwitcherActivity.class);
		intent.putExtra("otherid", device.getDeviceId());
		intent.putExtra("status", "1");
		intent.putExtra("devicelistid", device.getDeviceListId());
		startActivityForResult(intent, REQUEST_CODE_PAIZHAO);
	    } else {
		Toast.makeText(DeviceRoutingCheck.this, "请检查所有巡检项目！", Toast.LENGTH_SHORT).show();
	    }
	    break;
	case R.id.device_routing_check_rfid_tag:
		readtype="终端读卡";
	    if (isStop) {
		return;
	    }
	    rfidNumber = "";
	    if(readtype.equals("终端读卡")){
		  isNfc=true;
		  Toast.makeText(DeviceRoutingCheck.this, "正在读卡中，请将终端靠近标签", Toast.LENGTH_SHORT).show();
	    }else{
		isNfc=false;
		bluehelp.start();
		bluehelp.setRfidId("");
	    }
	   
	    time = System.currentTimeMillis();
	    isStop = true;
	  
	    new Thread() {

		@Override
		public void run() {
		    while (isStop) {
			if (!TextUtils.isEmpty(rfidNumber)&&readtype.equals("终端读卡")) {
			    Message msg = myHandler.obtainMessage();
			    msg.what = 1;
			    myHandler.sendMessage(msg);
			    isStop = false;
			    isNfc=false;
			}
			if(readtype.equals("蓝牙读卡")){
			    if(!TextUtils.isEmpty(bluehelp.getRfidId())){
				    rfidNumber=bluehelp.getRfidId();
				    Message msg = myHandler.obtainMessage();
				    msg.what = 1;
				    myHandler.sendMessage(msg);
				    isStop = false;
				    bluehelp.close();
				}
			}
			
			if (System.currentTimeMillis() - time > 10000) {
			    Message msg = myHandler.obtainMessage();
			    msg.what = 2;
			    myHandler.sendMessage(msg);
			    isStop = false;
			    if(readtype.equals("蓝牙读卡")){
				bluehelp.close();
			    }
			}
			try {
			    Thread.sleep(300);
			} catch (InterruptedException e) {
			    // TODO Auto-generated catch block
			    e.printStackTrace();
			}

		    }
		    super.run();
		}

	    }.start();
	    break;
	case R.id.device_routing_check_rfid_paizhao:
	    if (device == null) {
		Toast.makeText(DeviceRoutingCheck.this, "请先读卡确认此设备！", Toast.LENGTH_SHORT).show();
		return;
	    }
	    Intent intent = new Intent(DeviceRoutingCheck.this, ImageSwitcherActivity.class);
	    intent.putExtra("otherid", device.getDeviceId());
	    intent.putExtra("status", "1");
	    intent.putExtra("devicelistid", device.getDeviceListId());
	    startActivityForResult(intent, REQUEST_CODE_PAIZHAO);
	    break;
	default:
	    break;
	}

    }
    
    //返回事件
    public void btn_back(View view){
    	Intent  intent=new Intent(this, DeviceTaskActivity.class);
    	intent.putExtra("devicelistid", devicelistid);
    	setResult(RESULT_OK, intent);
    }

    public List<Integer> analyze(String infos) {

	info.clear();
	if (!TextUtils.isEmpty(infos) && infos.indexOf(",") > 0) {
	    String[] str = infos.split(",");

	    for (int i = 0; i < str.length; i++) {
		info.add(Integer.parseInt(str[i]));
	    }
	}

	if(!TextUtils.isEmpty(infos)&&infos.length()==1){
   	    info.add(Integer.parseInt(infos));
   	}
	if (info.size() == 0) {
	    for (int i = 0; i < item.size(); i++) {
		info.add(0);
	    }
	}
	return null;

    }

    @Override
    protected void onPause() {

	mAdapter.disableForegroundDispatch(this);

	super.onPause();
    }

    @Override
    protected void onResume() {
	mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);

	super.onResume();
    }

    @Override
    protected void onNewIntent(Intent intent) {
	if (!isNfc) {
	    return;
	}

	if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
	    Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
	    for (String tech : tagFromIntent.getTechList()) {
		System.out.println(tech);
	    }
	    time = System.currentTimeMillis();
	    MifareClassic mf = MifareClassic.get(tagFromIntent);
	    if (mf != null) {

		boolean auth = false;
		try {
		    mf.connect();
		    auth = mf.authenticateSectorWithKeyA(0, MifareClassic.KEY_DEFAULT);// 获取第一个扇区权限
		    if (auth) {
			byte[] date = mf.readBlock(0);// 读取block 0
			rfidNumber = CHexConver.bytesToHexStrings(date);
			Message msg = myHandler.obtainMessage();
			msg.what = 1;
			msg.obj = rfidNumber;
			myHandler.sendMessage(msg);
		    }

		} catch (IOException e) {

		    e.printStackTrace();
		} finally {
		    try {
			mf.close();
		    } catch (IOException e) {

			e.printStackTrace();
		    }
		}

	    }
	    NfcV nf = NfcV.get(tagFromIntent);
	    if (nf != null) {
		rfidNumber = CHexConver.bytesToHexStrings(nf.getTag().getId());
		Message msg = myHandler.obtainMessage();
		msg.what = 1;
		msg.obj = rfidNumber;
		myHandler.sendMessage(msg);
	    }

	}

	super.onNewIntent(intent);
    }

    Handler myHandler = new Handler() {

	@Override
	public void handleMessage(Message msg) {
	    if (msg.what == 1) {
		DeviceVo dev = dao.queryRfidDevice(rfidNumber, null, devicelistid);
		if (dev == null) {
		    Toast.makeText(DeviceRoutingCheck.this, "此标签未绑定设备", Toast.LENGTH_SHORT).show();
		    return;
		} else {

		    if (device != null) {

			if (!device.getDeviceListId().equals(dev.getDeviceListId())) {
			    item = dao.queryItems(dev.getDeviceListdeviceitem());
			    total = dao.queryAllDeviceTotal(dev.getDeviceListId());
			    nocopytotal = dao.queryNoCopyDeviceTotal(dev.getDeviceListId());
			    textinfo.setText("设备册总数:" + total + ", 未巡检数:" + nocopytotal);
			    // ArrayAdapter<String> adapter1=new
			    // ArrayAdapter<String>(DeviceRoutingCheck.this,
			    // android.R.layout.simple_spinner_item, data1);
			    // adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);//设置打开方式
			    // spinner1.setAdapter(adapter1);
			    // if(!TextUtils.isEmpty(device.getDevicestatus())){
			    // for(int i=0;i<data1.length;i++){
			    // if(data1[i].equals(device.getDevicestatus())){
			    // spinner1.setSelection(i, true);
			    // }
			    // }
			    // }

			    if (!TextUtils.isEmpty(device.getDeviceopenstatus())) {
				for (int i = 0; i < data2.size(); i++) {
				    if (data2.get(i).getKey().equals(device.getDeviceopenstatus())) {
					spinner2.setSelection(i, true);
				    }
				}
			    }
			}
		    } else {
			total = dao.queryAllDeviceTotal(dev.getDeviceListId());
			nocopytotal = dao.queryNoCopyDeviceTotal(dev.getDeviceListId());
			String str = "设备册总数:" + total + ", 未巡检数:" + nocopytotal;
			System.out.println(textinfo == null);
			textinfo.setText(str);
			item = dao.queryItems(dev.getDeviceListdeviceitem());
		    }
		    analyze(dev.getCopydata());
		    device = dev;
		    edit.setText(device.getRemark());
		    initData();
		    adapter.setInfo(info);
		    adapter.setItem(item);
		    adapter.notifyDataSetChanged();
		}
	    } else if (msg.what == 2) {
		Toast.makeText(DeviceRoutingCheck.this, "读卡超时", Toast.LENGTH_SHORT).show();
	    }
	    super.handleMessage(msg);
	}

    };

    public void initData() {
	textview2.setText(device.getDeviceNumber());
	textview3.setText(device.getDeviceAdds());
	textview3.setSelected(true);
	textview4.setText(device.getDeviceCaliber());
	textview5.setText(device.getDeviceType());

    }

    // 检测所巡检项目是否选择完毕
    public boolean isSelectAll(List<Integer> list) {
	boolean b = true;

	for (int i = 0; i < list.size(); i++) {

	    if (list.get(i) == 0) {
		return false;
	    }
	}
	return b;

    }

    public String checkdata(List<Integer> list) {
	String str = "";
	for (int i = 0; i < list.size(); i++) {
	    str = str + list.get(i) + ",";
	}
	return str.substring(0, str.length() - 1);
    }

    @Override
    protected void onDestroy() {
	dao.close();
	if(bluehelp!=null){
	    bluehelp.stop();
	}
	super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	if (requestCode == REQUEST_CODE_PAIZHAO) {
	    if (resultCode == RESULT_OK) {
		if (isSave) {
		    boolean b = dao.insertDeviceData(device.getDeviceId(), checkdata(adapter.getInfo()), "0", edit.getEditableText().toString(), devicelistid, openstatus);
		    if (b) {
			Toast.makeText(DeviceRoutingCheck.this, "添加成功", Toast.LENGTH_SHORT).show();
		    } else {
			Toast.makeText(DeviceRoutingCheck.this, "添加失败", Toast.LENGTH_SHORT).show();
		    }
		    isSave = false;
		}

	    } else if (requestCode == RESULT_CANCELED) {
		if (!isSave) {
		    return;
		}
		Toast.makeText(DeviceRoutingCheck.this, "你没有拍照不会保存数据", Toast.LENGTH_SHORT).show();
	    }
	}
	super.onActivityResult(requestCode, resultCode, data);
    }

}
